/**
 * @description    考核指标管理控制层
 * @author         秦俊强
 * @email          458112865@qq.com
 * @create         2020-03-12 21:50
 * */

/* 引入弹窗表单组件 */
import AddTreeNode from './AddTreeNode';

/* api 通用服务 */
import { apiService } from '@/api/api.service.js';

/**
 * api 接口
 *
 * getOrgTypes => 【获取】可选部门信息
 * getIndexTree => 【获取】指标树
 *
 * queryAttrs => 【获取】树节点详细信息
 * getListAttrs => 【获取】指标和指标值属性信息
 *
 * delNode => 【删除】树节点
 * addNode => 【新增】树节点
 * modifyAttrs => 【保存】节点详细信息
 *
 * orderIndexs => 【排序】树节点
 * */
import {
  getOrgTypes, getIndexTree,
  queryAttrs, getListAttrs,
  delNode, addNode, modifyAttrs,
  orderIndexs
} from '@/api/api.js';





export default {
  components: { AddTreeNode },

  data() {
    return {
      loading: true,
      isDraggable: false,   // 是否排序

      /* 部门信息 */
      orgTypes: {
        arr: [],
        value: {}
      },

      /* 数据树 */
      treeData: [],

      /* 排序状态的数据树 */
      dropTreeData: [],

      /* 当前选中的树节点 */
      selectedTree: {},

      /* 指标和指标值的属性 */
      listAttrs: {},

      /* 指标详细信息 */
      attrsDetail: {},

      /* 表单布局 */
      formLayout: {
        auto: {
          labelCol: { span: 10 },
          wrapperCol: { span: 9 }
        },

        tail: {
          wrapperCol: {
            xs: { offset: 0 },
            sm: { offset: 10 },
          }
        }
      },

      /* 弹窗添加节点 */
      modalInfo: {
        show: false,
        title: '添加指标项',
        autoKey: ''
      }
    }
  },

  /* 数据初始化 */
  created() {
    this.getOrgTypes();
    this.initListAttrs();
  },

  methods: {
    /* 监听部门切换 */
    changeOrg(e) {
      let val = e.target.value;
      let arr = this.orgTypes.arr;
      this.orgTypes.value = arr.find((item) => { return (item.code === val); });
      this.getTreeData();
    },

    /* 选择 | 取消节点 */
    selected(keys, e) {
      this.selectedTree = {};
      this.attrsDetail = { edit: null, res: null };

      if (e.selected) {
        this.operTreeData(this.treeData, keys[0], 'query');

        // 递归操作树结构可能需要一点时间，所以延时执行
        setTimeout(() => { this.queryAttrs(); }, 100);
      }
    },

    /* 切换是否是排序状态 */
    switchDraggableType(str) {
      if (str === 'success') {
        this.treeData = JSON.parse(JSON.stringify(this.dropTreeData));

        // 通知弹窗组件更新 treeData
        if (this.$refs.addNode) { this.$refs.addNode.updateNewSelectTree(this.treeData); }
      } else {
        this.selectedTree = {};

        if (!this.isDraggable) {
          this.dropTreeData = JSON.parse(JSON.stringify(this.treeData));
        } else {
          this.dropTreeData = [];
        }
      }

      this.isDraggable = !this.isDraggable;
    },

    /* 保存排序后的树数据 */
    saveOrderTree() {
      this.loading = true;
      apiService(orderIndexs(this.dropTreeData[0])).then((res) => {
        this.loading = false;
        this.switchDraggableType('success');
      }).catch((error) => {
        this.loading = false;
        this.$message.error(error.message);
      });
    },

    /* 排序参考文档 https://www.antdv.com/components/tree-cn/#components-tree-demo-draggable */
    onDrop(info) {
      let dropKey = info.node.eventKey;
      let dragKey = info.dragNode.eventKey;
      let dropPos = info.node.pos.split('-');
      let dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);

      // 不允许将子级放在顶层
      if (dropPos.length <= 2) {
        this.$message.warning('暂不支持指标项和所属部门平级。');
        return;
      }

      let loop = (data, key, callback) => {
        data.forEach((item, index, arr) => {
          if (item.key === key) {
            return callback(item, index, arr);
          }
          if (item.children) {
            return loop(item.children, key, callback);
          }
        });
      };
      let data = [...this.dropTreeData];

      // Find dragObject
      let dragObj;
      loop(data, dragKey, (item, index, arr) => {
        arr.splice(index, 1);
        dragObj = item;
      });
      if (!info.dropToGap) {
        // Drop on the content
        loop(data, dropKey, item => {
          item.children = item.children || [];
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.push(dragObj);
        });
      } else if (
        (info.node.children || []).length > 0 && // Has children
        info.node.expanded && // Is expanded
        dropPosition === 1 // On the bottom gap
      ) {
        loop(data, dropKey, item => {
          item.children = item.children || [];
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.unshift(dragObj);
        });
      } else {
        let ar;
        let i;
        loop(data, dropKey, (item, index, arr) => {
          ar = arr;
          i = index;
        });
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj);
        } else {
          ar.splice(i + 1, 0, dragObj);
        }
      }
      this.dropTreeData = data;
    },

    /* 添加指标弹窗信息 */
    showAddIndex(item) {
      this.modalInfo.autoKey = item.key;
      this.modalInfo.show = true;
    },

    /* 添加指标节点 */
    addTreeNode() {
      let nodeInfo = this.$refs.addNode.nodeInfo;
      let param = {
        "parentKey": nodeInfo.parentKey,
        "type": nodeInfo.type,
        "title": nodeInfo.title
      };

      this.loading = true;
      apiService(addNode(param)).then((res) => {
        this.$message.success('指标添加成功！');
        this.modalInfo.show = false;
        this.getTreeData();
      }).catch((error) => {
        this.loading = false;
        this.$message.error(error.message);
      });
    },

    /* 删除指标确认弹窗 */
    showDeleteConfirm(item) {
      let t = this;
      let title = item.title + '（' + item.key + '）';
      let content = item.type === 'index' ? '注意：如果该项存在子级，也将会一起删除！' : '';

      t.$confirm({
        title: '确定要删除【' + title +  '】吗？',
        content: content,
        width: '520px',
        okText: '删除',
        cancelText: '关闭',
        okType: 'danger',
        icon: 'exclamation-circle',
        onOk() { t.deleteIndex(item); }
      });
    },

    /* 删除节点 */
    deleteIndex(item) {
      let param = {
        type: item.type,
        key: item.key,
        code: item.code
      };

      this.loading = true;
      apiService(delNode(param)).then((res) => {
        this.loading = false;
        this.treeData = this.operTreeData(this.treeData, param.key, 'del');
      }).catch((error) => {
        this.loading = false;
        this.$message.error(error.message);
      });
    },

    /* 获取数据树 */
    getTreeData() {
      let param = { indexGroup: this.orgTypes.value.code }

      this.loading = true;
      apiService(getIndexTree(param)).then((res) => {
        this.loading = false;
        this.isDraggable = false;
        this.selectedTree = {};

        this.treeData = this.operTreeData([res.result]);

        // 通知弹窗组件更新 treeData
        if (this.$refs.addNode) { this.$refs.addNode.updateNewSelectTree(this.treeData); }
      }).catch((error) => {
        this.loading = false;
        this.$message.error(error.message);
      });
    },

    /**
     * 用递归操作树节点，因为树结构不确定会有多少层级
     *
     * @param   { Array }     tree => [{ key: '', code: '', children: [], ... }]
     * @param   { String }    code => 树节点的 code
     * @param   { String }    type => 'del' 移除 | 'query' 查找某个节点 | 'format' 格式化（默认）
     *
     * @return  { Array }
     * */
    operTreeData(tree, key, type) {
      let newTree = [];

      if (!tree) { return newTree; }

      // 从数组最后一个开始循环，因为涉及删除操作
      for (let i = tree.length - 1; i >= 0; i--) {
        let item = tree[i];

        // 查找树节点中选中节点的信息
        if (type === 'query') {
          if (item.key === key && !this.selectedTree[key]) {
            this.selectedTree = {
              key: item.key,
              title: item.title,
              editTitle: item.title,    // 用于编辑时输入框中显示
              code: item.code,
              type: item.type
            };
          } else {
            this.operTreeData(item.children, key, type);
          }
          continue;
        }

        // 本地静态移除，需要移除的节点忽略
        if (type === 'del' && item.key === key) { continue; }

        // 将数组放在最前面
        newTree.unshift({
          key: item.key,
          title: item.title,
          code: item.code,
          value: item.key,
          type: item.type || 'indexGroup',
          scopedSlots: { title: item.type || 'indexGroup' }
        });

        // 因为是 unshift，所以永远是第 0 个
        if (item.children) {
          if (item.children.length > 0) {
            newTree[0].childrenLen = item.children.length;
          }

          newTree[0]['children'] = [];
          newTree[0]['children'] = this.operTreeData(item.children, key, type);
        }
      }

      return newTree;
    },

    /* 获取节点详细信息 */
    queryAttrs() {
      let param = {
        type: this.selectedTree.type,
        key: this.selectedTree.key,
        code: this.selectedTree.code
      };

      this.loading = true;
      apiService(queryAttrs(param)).then((res) => {
        this.loading = false;

        if (!res.result) {
          this.$message.warning(res.message);
          return;
        }

        if (res.result.length === 0) {
          this.$message.warning('详细信息为空，请联系管理员');
          return;
        }

        /* TODO 已 attrCode 为 key 临时将数组转成对象 */
        let detailObj = {};
        for (let i = 0; i < res.result.length; i++) {
          let item = res.result[i];
          detailObj[item.attrCode] = item;
        }

        this.attrsDetail.edit = detailObj;    // 用于前端编辑数据
        this.attrsDetail.res = JSON.parse(JSON.stringify(detailObj));   // 用于比较和还原数据
      }).catch((error) => {
        this.loading = false;
        this.$message.error(error.message);
      });
    },

    /* TODO 监听 form input 变化 */
    changeFormInput(e, code) {
      // this.attrsDetail.edit[code].attrValue = e.target.value;
    },

    /* TODO 监听 form select 变化 */
    changeFormSelect(val, code, ind) {
      /*console.log(val, code, ind);
      let arr = this.getAttrs();
      console.log(arr);*/
    },

    /* 保存节点数据 */
    saveAttr() {
      let selectedTree = this.selectedTree;
      let attrsDetail = this.attrsDetail;

      let param = {
        "type": selectedTree.type,
        "key": selectedTree.key,
        "title": selectedTree.editTitle,
        "attrs": Object.values(attrsDetail.edit)
      };

      this.loading = true;
      apiService(modifyAttrs(param)).then((res) => {
        this.$message.success('保存成功！');
        this.loading = false;
        this.updateAttrDetail('save');
      }).catch(() => {
        this.loading = false;
        this.$message.error(error.message);
      });
    },

    /* 保存节点成功后 更新详细节点 */
    updateAttrDetail(str) {
      let attrsDetail = this.attrsDetail;
      if (str === 'save') {
        let newData = attrsDetail.edit;
        this.attrsDetail.res = JSON.parse(JSON.stringify(newData));
        return;
      }

      if (str === 'cancel') {
        let res = attrsDetail.res;
        this.attrsDetail.edit = JSON.parse(JSON.stringify(res));
      }
    },

    /* 是否可提交保存 */
    isDisabled() {
      let attrsDetail = this.attrsDetail;
      let selectedTree = this.selectedTree;
      if (selectedTree.editTitle !== selectedTree.title) { return false; }

      for (let key in attrsDetail.edit) {
        let item = attrsDetail.edit[key];
        if (item.attrValue !== attrsDetail.res[key].attrValue) { return false; }
      }

      return true;
    },

    /* 获取部门信息 */
    getOrgTypes() {
      apiService(getOrgTypes()).then((res) => {
        let result = res.result;
        this.orgTypes.arr = result.orgTypes;
        this.orgTypes.value = result.orgTypes[0];

        this.getTreeData();
      }).catch((error) => {
        this.$message.error(error.message);
      });
    },

    /* 初始化指标和指标值的属性信息 */
    initListAttrs() {
      apiService(getListAttrs({ type: '' })).then((res) => {
        this.listAttrs = res.result;
      }).catch((error) => {
        this.$message.error(error.message);
      });
    },

    /* 返回需要循环的指标项属性数组 */
    getAttrs() {
      let selectedTree = this.selectedTree;
      if (selectedTree.type === 'index') {
        return this.listAttrs.indexAttrs;
      }
      if (selectedTree.type === 'indexValue') {
        return this.listAttrs.indexValueAttrs;
      }
    },

    /* 返回文字信息 */
    getTitleSize(item, isTitle) {
      let size = item.title + ' [ ' + item.key + ' ]';

      if (isTitle) { return size; }
      return (typeof item.childrenLen === 'number') ? (size + '（' + item.childrenLen + '）') : size;
    },

    /* 返回提示文字 */
    getMessage() {
      let selectedTree = this.selectedTree;
      let title = '提示：';

      if (this.isDraggable) { return title + '按住鼠标左键上下拖动指标项可进行排序。'; }

      if (selectedTree.key) {
        return title + '当前已选中指标项「' + selectedTree.title + '（' + selectedTree.key + '）」，再次点击即可取消选择。';
      }

      return title + '选中左侧任意项，可在右侧进行详情查看或编辑。';
    }

  }
}
